package com.hethongviet.preventingmachine.helps;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.hethongviet.preventingmachine.Utils;
import com.hethongviet.preventingmachine.helps.db.MySQLiteHelper;

public class DeviceSQLite
{
	public static final String TABLE_NAME = "device";

	public static final String COLUMN_ID_DB = "idDB";

	public static final String COLUMN_NUMBER = "phone_number";
	public static final String COLUMN_NAME = "name";
	public static final String COLUMN_PIN = "pin";

	// Database fields
	private SQLiteDatabase _database;
	private MySQLiteHelper _dbHelper;
	private String[] _allColumns = { COLUMN_ID_DB,
	COLUMN_NUMBER, COLUMN_NAME, COLUMN_PIN };

	public static final String STRING_COLUMNS = COLUMN_ID_DB
			+ " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, "
			+ COLUMN_NUMBER + " text, " + COLUMN_NAME + " text, " + COLUMN_PIN
			+ " text";

	public DeviceSQLite(Context context, String databaseName)
	{
		List<String> tableNames = new ArrayList<String>();
		List<String> columnNames = new ArrayList<String>();

		tableNames.add(TABLE_NAME);
		columnNames.add(STRING_COLUMNS);

		_dbHelper = new MySQLiteHelper(context, tableNames, columnNames,
				databaseName);
	}

	public void open() throws SQLException
	{
		_database = _dbHelper.getWritableDatabase();
	}

	public void close()
	{
		_dbHelper.close();
	}

	private boolean dataExist(Device device, Cursor cursor)
	{
		if (cursor == null)
		{
			return false;
		}
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
		{
			long idDB = cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB));
			if (idDB == device.getIdDB())
				return true;
		}
		return false;
	}

	/**
	 * @param device
	 * @return row id -1: insert fail
	 */
	public long insert(Device device)
	{
		Utils.debug("insert -- device : " + device.getNumber());
		open();

		Cursor cursor = _database.rawQuery("SELECT * FROM " + TABLE_NAME
				+ " WHERE " + COLUMN_ID_DB + " = " + device.getIdDB(), null);

		long temp = -1;
		if (!dataExist(device, cursor))
		{
			Utils.debug("insert 1111111111111 INSERT");
			/* Insert to database */
			/* Insert new */
			Cursor cursorInsert = _database.rawQuery("INSERT INTO "
					+ TABLE_NAME + "(" + COLUMN_NUMBER + ", " + COLUMN_NAME+ ", " + COLUMN_PIN
					+ ") values( ?, ?, ?)",

			new String[] { device.getNumber(), device.getName() , device.getPin()});

			cursorInsert.moveToFirst();
			if (!cursorInsert.isAfterLast())
				temp = cursorInsert.getLong(cursorInsert.getColumnIndex(COLUMN_ID_DB));

			cursorInsert.close();
		}
		else
		{
			Utils.debug("insert 1111111111111 update");

			ContentValues contentValues = new ContentValues();
			contentValues.put(COLUMN_NUMBER, device.getNumber());
			contentValues.put(COLUMN_NAME, device.getName());
			contentValues.put(COLUMN_PIN, device.getPin());

			temp = _database.update(TABLE_NAME, contentValues, COLUMN_ID_DB
					+ " = " + device.getIdDB(), null);
		}
		cursor.close();
		close();
		return temp;
	}

	public void deleteAll()
	{
		open();

		System.out.println("project deleted all");
		// _database.rawQuery("DELETE FROM " + TABLE_NAME, null); not work
		// _database.rawQuery("DELETE FROM " + TABLE_NAME + " WHERE 1", null);
		_database.delete(TABLE_NAME, "1", null);
		close();
	}

	public List<Device> getAll()
	{
		open();

		List<Device> listDevices = new ArrayList<Device>();

		Cursor cursor = _database.query(TABLE_NAME, _allColumns, null, null,
				null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast())
		{
			Device device = cursorToDevice(cursor);
			listDevices.add(device);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		close();
		return listDevices;
	}

	private Device cursorToDevice(Cursor cursor)
	{
		Device device = new Device();
		device.setIdDB(cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB)));
		device.setNumber(cursor.getString(cursor.getColumnIndex(COLUMN_NUMBER)));
		device.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
		device.setPin(cursor.getString(cursor.getColumnIndex(COLUMN_PIN)));
		return device;
	}

	public final boolean isTableExist()
	{
		open();

		boolean isExist = false;
		Cursor cursor = _database.rawQuery(
				"select DISTINCT tbl_name from sqlite_master where tbl_name = '"
						+ TABLE_NAME + "'", null);
		isExist = cursor != null && cursor.getCount() > 0;

		cursor.close();
		close();

		return isExist;
	}
}
